import { fileURLToPath, URL } from 'node:url'
import { defineConfig, loadEnv} from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'

// elemment-plus按需导入  自动导入配置
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
// elemment-plus按需导入  自动导入配置

// 兼容低版本浏览器
import legacy from '@vitejs/plugin-legacy'
// 兼容低版本浏览

export default ({mode}) => {
  const envPrefix = "VITE_"
  const ENV = loadEnv(mode, './', envPrefix)
  const { VITE_PUBLIC_PATH, VITE_PROXY } = ENV
  return defineConfig({
    envPrefix,
    base:VITE_PUBLIC_PATH,
    // publicPath:ENV.PROD ? './' : "/",
    // outputDir:'dist',
    // indexPath:"index.html",
    build: {
      chunkSizeWarningLimit:1500,
      rollupOptions:{
        output:{
          manualChunks(id){
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          }
        }
      }
    },
    plugins: [
      vue(),
      vueJsx(),

      // elemment-plus按需导入  自动导入配置
      AutoImport({
        resolvers: [ElementPlusResolver()],
      }),
      Components({
        resolvers: [ElementPlusResolver()],
      }),
      // elemment-plus按需导入  自动导入配置

      // 兼容低版本浏览器
      legacy({
        targets: ['defaults', 'ie >= 11', 'chrome 52'],  //需要兼容的目标列表，可以设置多个
        additionalLegacyPolyfills: ['regenerator-runtime/runtime'],
        renderLegacyChunks:true,
        polyfills:[
          'es.symbol',
          'es.array.filter',
          'es.promise',
          'es.promise.finally',
          'es/map',
          'es/set',
          'es.array.for-each',
          'es.object.define-properties',
          'es.object.define-property',
          'es.object.get-own-property-descriptor',
          'es.object.get-own-property-descriptors',
          'es.object.keys',
          'es.object.to-string',
          'web.dom-collections.for-each',
          'esnext.global-this',
          'esnext.string.match-all'
      ]
      }),
      // 兼容低版本浏览器
    ],
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    server:{
      host:"0.0.0.0",
      port:8080,
      // open:true,
      proxy: (function (ProxyList = []) {
        const ProxyTargetList = {};
        for (const [prefix, target] of ProxyList) {
          const isHttps = /^https:\/\//.test(target);
          ProxyTargetList[prefix] = {
            target,
            changeOrigin: true,
            ws: true,
            rewrite: (path) => {
              return path.replace(new RegExp(`^${prefix}`), '')
            },
            ...(isHttps ? { secure: false } : {}),
          };
        }
        return ProxyTargetList;
      }(VITE_PROXY && JSON.parse(VITE_PROXY)))
    }
  })  
}

